
package hk.ces.oxfam.patch.patchs;

import hk.ces.oxfam.patch.DBPatch;
import hk.ces.oxfam.patch.db.result.ExcuteResult;
import hk.ces.oxfam.patch.db.sql.PreparedSQL;
import hk.ces.oxfam.patch.db.result.SQLResult;
import hk.ces.oxfam.patch.db.sql.SQLUtil;
import hk.ces.oxfam.patch.xml.SQLResultXML;
import hk.ces.oxfam.patch.xml.factory.SQLResultXMLFactory;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.Logger;

/**
 *
 * @author ReutyCheng
 */
public class OnlinePrintCountPatch implements DBPatch
{
  private static final String TXMETHOD_ONLINE = "ONLINE";
  private static final String TXSTATE_CONFIRM = "CONFIRM";
  private static final String PRINTTYPE_E_RECEIPT = "E_RECEIPT";
  private static final int PRINTCOUNT_ZERO = 0;
  private static final int PRINTCOUNT_ONE = 1;

  public String getName()
  {
    return "Update Online Donation and E-Receipt Transaction, set Print Count [0] to [1] DB Patch";
  }

  public void patch(Connection connection) throws SQLException
  {
    SQLResult result = getOnlineEReceiptIds(connection);
    SQLResultXMLFactory factory = new SQLResultXMLFactory("OnlineE-Receipt.xml");
    factory.setXMLItems(new SQLResultXML(result));
    factory.writeToFile();

    Logger.getLogger(this.getClass()).debug("Online Donation and E-Receipt and PrintCount is 0 - Size : " + result.getRowCount());

    int resultCount = this.updatePrintCount(connection);
    Logger.getLogger(this.getClass()).debug("Totally update Receipt[count=" + resultCount + "]");
  }

  private int updatePrintCount(Connection connection) throws SQLException
  {
    String sql = "update receipt set printcount = ? where id in (select id from receipt where "
            + "id in (select receipt_id from transaction where method = ? and disabled = ? and transactionstate = ?)"
            + " and printtype = ? and printcount = ? and disabled = ?)";
    Object[] params = new Object[]{PRINTCOUNT_ONE, TXMETHOD_ONLINE, false, TXSTATE_CONFIRM, PRINTTYPE_E_RECEIPT, PRINTCOUNT_ZERO, false};
    ExcuteResult excuteResult = SQLUtil.execute(connection, new PreparedSQL(sql, params));
    return excuteResult.getResultCount();
  }

  private SQLResult getOnlineEReceiptIds(Connection connection) throws SQLException
  {
    String sql = "select id, name from receipt where "
            + "id in (select receipt_id from transaction where method = ? and disabled = ? and transactionstate = ?)"
            + " and printtype = ? and printcount = ? and disabled = ?";
    Object[] objects = new Object[]
    {
      TXMETHOD_ONLINE, false, TXSTATE_CONFIRM, PRINTTYPE_E_RECEIPT, PRINTCOUNT_ZERO, false
    };

    SQLResult result = SQLUtil.query(connection, new PreparedSQL(sql, objects));
    return result;
  }
}
